#include "Matrix_TBB.h"
#include <memory.h>
#include "CalculationTask.h"

#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>

#include <time.h>

using namespace tbb;

SparseMatrix SparseMatrix_TBB::Multiplication(SparseMatrix B)
{
	SparseMatrix C;

	int i;

	task_scheduler_init init();

	vector<int>* rows = new vector<int>[N]; 
	vector<float> *values = new vector<float>[N];
	int* colIndex = new int[N + 1]; 
	
	memset(colIndex, 0, sizeof(int) * N); 

	int grainsize = 10; 

	parallel_for(blocked_range<int>(0, this->N, grainsize),
		Task_Multiplicator(this->Transpose(), B, rows, values, colIndex)); 
	
	int NZ = 0; 
	for(i = 0; i < N; i++)
	{ 
		int tmp = colIndex[i]; 
		colIndex[i] = NZ;
		NZ += tmp;
	} 
	colIndex[N] = NZ;

	C.N = N;
	C.size = NZ;
	C.Value = new float[NZ];
	C.Row = new int[NZ]; 
	C.ColIndex = new int[N + 1];
	
	int count = 0; 
	for (i = 0; i < N; i++) 
	{ 
		int size = rows[i].size();
		if (size !=0)
		{
			memcpy(&C.Row[count], &rows[i][0], size * sizeof(int));
			memcpy(&C.Value[count], &values[i][0], size * sizeof(float));
			count += size; 
		}
	} 
	memcpy(C.ColIndex, &colIndex[0], (N + 1) * sizeof(int)); 
	
	return C;
}

